<?php

namespace App\Console\Commands;

use App\Models\SeckillGood;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

class SeckillCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'SeckillCommand';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public $redis;

    public function __construct()
    {
        parent::__construct();
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1', 6379);
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        //不是当天的秒杀商品预热库存d
        $sameDay = date('Y-m-d');
        //开始商品
        $preheatGoods = (new SeckillGood())->with('goodsTime')->where('seckill_state', 1)->where('start_time', $sameDay)->get()->toArray();
        //dd($preheatGoods);
        //循环放入redis
        foreach ($preheatGoods as $k => $v) {
            //开始时间和结束时间
            $startTime = $v['start_time'] . ' ' . intval($v['goods_time'][0]['start_time']) . ':' . '00' . ':' . '00';
            $endTime = $v['start_time'] . ' ' . intval($v['goods_time'][0]['start_time'] + $v['goods_time'][0]['continued_time']) . ':' . '00' . ':' . '00';
            //dd($endTime);
            for ($i = 0; $i <= $v['seckill_count']; $i++) {
                //将数据存放到列表中
                Redis::lPush('number_' . $v['id'], 1);
            }
            //根据结束时间-当前时间设置为过期时间，缓存消失则活动结束
            //存这条秒杀商品的开始时间
            Redis::set('start_time_' . $v['id'], strtotime($startTime), strtotime($endTime) - time());
        }
        return 0;
    }
}